# Makefile
# David Grant, 2004
# Irene Huang, 2010/05/03 
# Mikhail Zakharov, 2010/05/11

#where all the headders are
INC=-Icommon/

#define your ifdef flags here

#uncomment this flag to build for CF_SERVER
DEFINES+=-D_CFSERVER_

#optimization level
#OPT=-Os



#add gdb to the list of includes
ifeq ($(GDB_SESSION),ON)
DEFINES+=-D_GDB_
INC+=-Igdb_src/
LIBGDB=-static -Lgdb_src 
ifneq (,$(findstring CFSERVER,$(DEFINES)))
LIBGDB+=-lgdb_cf
else
LIBGDB+=-lgdb
endif
endif

ifneq (,$(findstring CFSERVER,$(DEFINES)))
GDB_HOST=cf-server.uwaterloo.ca
else
GDB_HOST=localhost
endif

#default gdb host target
ifneq ($(GPORT),"")
GPORT=5207
endif



CFLAGS=-Wall $(OPT) -Werror -m5307 -pipe -nostdlib ${INC} ${DEFINES}


SYSTEM=$(shell uname)
CC=m68k-elf-gcc -g
ifneq ($(SYSTEM),Linux)
COLDFIRE_EMU=coldfire.exe
else
COLDFIRE_EMU=coldfire
endif
BOARD=--board cjdesign-5307.board
CXX=m68k-elf-g++
LD=m68k-elf-gcc
AS=m68k-elf-as
ifneq ($(SYSTEM),Linux)
GDB=m68k-elf-gdb.exe
else
GDB=m68k-elf-gdb
endif
AR=m68k-elf-ar
ARFLAGS=
OBJCPY=m68k-elf-objcopy
OBJDMP=m68k-elf-objdump
ifneq ($(SYSTEM),Linux)
KILLER=taskkill /F /IM 
else
KILLER=killall
endif

ASM=common/start.s
LDFLAGS+=-Tcommon/rtx.ld -Wl,-Map=main.map 
MAIN_OBJS+=dbug/dbug.o utils.o

default:main.s19

all:
	make clean
	make libgdb
	make debug

# Note, GCC builds things in order, it's important to put yhe
#  ASM first, so that it is located at the beginning of our program.
main.s19: $(MAIN_OBJS) main.c
	$(CC)  $(CFLAGS) $(LDFLAGS) -o main.bin  $(ASM) main.c $(LIBGDB) $(MAIN_OBJS) 
	$(OBJCPY) --output-format=srec main.bin main.s19
	cp main.s19 rtx.s19
	$(OBJDMP) -xdC main.bin > main.lst 
#create a gdb library
libgdb:
	cd gdb_src && make libgdb && make libgdb_cf
#create a gdb library for cf-server (different baud rate for uart)

clean:
	rm -f *.s19 *.o *.orig *.bin *.lst *.map gdb_src/*.o dbug/*.o

#use this to compile with the gdb stub support
#we need to remove main.s19 every time since we would
#like to recompile without gdb hooks on regular make
debug:
	make gdbinit
	rm -f main.s19
	make GDB_SESSION=ON main.s19
	rm -f main.s19

#starts console gdb session
gdb:
	$(GDB) main.bin

gdbinit:
	echo target remote $(GDB_HOST):$(GPORT) > .gdbinit


#kills all coldfire and gdb processes on windows and linux
kill:
	-$(KILLER) $(COLDFIRE_EMU)
	-$(KILLER) $(GDB)

#starts the emulator, downloads the main binary, and executes
emu:
	${COLDFIRE_EMU} ${BOARD} --commands "dl main.s19,go 10100000"
#just starts the emulator
cold:
	${COLDFIRE_EMU} ${BOARD}

#generate tags for vim
tag:
	ctags -R --language-force=c .
#make sure ecelinux doesnt complain
dos2unix:
	find . | awk '{print "\""$$1"\""}' | xargs dos2unix
